package cn.js.sangu.unitStore.controller;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.entity.Setting;
import cn.js.sangu.unitStore.service.SettingService;

/**
 * 设置控制器
 * 适配MyBatis Plus优化后的Service层接口
 */
@RestController
@RequestMapping("/api/setting")
// 已有全局跨域设置CorsConfig
public class SettingController {

    static final String OPERATION_SETTINGS = "高级设置";

    @Autowired
    private SettingService settingService;

    /**
     * 获取所有设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.LOOKUP)
    @GetMapping("/all")
    public R getAllSettings() {
        return R.ok(settingService.getAllSettings());
    }

    /**
     * 根据模块获取设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.LOOKUP)
    @GetMapping("/module/{module}")
    public R getSettingsByModule(@PathVariable String module) {
        return R.ok(settingService.getSettingsByModule(module));
    }

    /**
     * 根据模块获取设置Map格式
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.LOOKUP)
    @GetMapping("/module/{module}/map")
    public R getModuleSettingsMap(@PathVariable String module) {
        try {
            Map<String, Object> settingsMap = settingService.getModuleSettingsMap(module);
            if (settingsMap == null || settingsMap.isEmpty()) {
                // 如果没有找到设置，返回空对象而不是null，并添加状态说明
                return R.ok("未查询到模块设置数据");
            }
            return R.ok(settingsMap);
        } catch (Exception e) {
            return R.fail("查询设置失败：" + e.getMessage());
        }
    }

    /**
     * 根据键名获取设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.LOOKUP)
    @GetMapping("/key/{key}")
    public R getSettingByKey(@PathVariable String key) {
        return R.ok(settingService.getSettingByKey(key));
    }

    /**
     * 保存单个设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.UPDATE)
    @PostMapping("/save")
    public R saveSetting(@RequestBody Setting setting) {
        try {
            boolean success = settingService.saveSetting(setting);
            return success ? R.ok("保存成功") : R.fail("保存失败");
        } catch (Exception e) {
            return R.fail("保存失败：" + e.getMessage());
        }
    }

    /**
     * 批量保存设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.UPDATE)
    @PostMapping("/batch/save")
    public R batchSaveSettings(@RequestBody List<Setting> settings) {
        try {
            boolean success = settingService.batchSaveSettings(settings);
            return success ? R.ok("批量保存成功") : R.fail("批量保存失败");
        } catch (Exception e) {
            return R.fail("批量保存失败：" + e.getMessage());
        }
    }

    /**
     * 删除设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.DELETE)
    @DeleteMapping("/delete/{key}")
    public R deleteSetting(@PathVariable String key) {
        try {
            boolean success = settingService.deleteSetting(key);
            return success ? R.ok("删除成功") : R.fail("删除失败");
        } catch (Exception e) {
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 初始化Bom模块默认设置
     */
    @MyLogsAOP(operation = OPERATION_SETTINGS, operaType = LogType.UPDATE)
    @PostMapping("/init/bom")
    public R initBomSettings() {
        try {
            // 初始化唯一性设置
            Setting uniqueTypeSetting = new Setting();
            uniqueTypeSetting.setK("bom.unique_type");
            uniqueTypeSetting.setV("1"); // 默认绝对唯一
            uniqueTypeSetting.setModule("bom");
            uniqueTypeSetting.setDescription("BOM唯一性类型设置(0:相对唯一, 1:绝对唯一)");
            uniqueTypeSetting.setType("number");
            settingService.saveSetting(uniqueTypeSetting);
            
            // 初始化问号处理方式设置
            Setting questionMarkSetting = new Setting();
            questionMarkSetting.setK("bom.question_mark_handle");
            questionMarkSetting.setV("1"); // 默认替换问号为随机数
            questionMarkSetting.setModule("bom");
            questionMarkSetting.setDescription("BOM编码问号处理方式(0:保留问号, 1:替换问号为随机数, 2:替换问号为零)");
            questionMarkSetting.setType("number");
            settingService.saveSetting(questionMarkSetting);
            
            // 初始化匹配模式设置
            Setting matchModeSetting = new Setting();
            matchModeSetting.setK("bom.match_mode");
            matchModeSetting.setV("1"); // 默认模糊匹配 (0:精准匹配, 1:模糊匹配)
            matchModeSetting.setModule("bom");
            matchModeSetting.setDescription("BOM编码匹配模式(0:精准匹配, 1:模糊匹配)");
            matchModeSetting.setType("number");
            settingService.saveSetting(matchModeSetting);
            
            return R.ok("BOM模块设置初始化成功");
        } catch (Exception e) {
            return R.fail("初始化失败：" + e.getMessage());
        }
    }
}
